package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.bean.User;
import com.itheima.commons.R;
import com.itheima.exception.CustomException;
import com.itheima.service.UserService;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author Tang
 * @date 2023/1/10
 */
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 获取验证+发送短信
     * @param phone
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //1.获取前端传递的手机号
        //2.调用生成验证码工具类来生成验证码code, 缓存验证码  用session缓存    //用redis缓存数据
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        log.info("验证码：{}",code);
        session.setAttribute(user.getPhone(), code);

        //3.调用阿里云API给对应的手机号发送短信
        //SMSUtils.sendMessage("瑞吉外卖", "SMS_xxxxxx", phone, code);

        //4.返回结果R<String>  验证码返回给前端(为了方便测试)
        return R.success(code);
    }

    /**
     * 用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody Map<String, String> map, HttpSession session){
        //1.获取前端传递的手机号以及验证码
        String phone = map.get("phone");
        String code = map.get("code");

        //2.校验验证码：从session中获取验证码与前端传递过来的验证码作比较
        Object validateCode = session.getAttribute(phone);
        if (validateCode == null) {
            throw new CustomException("验证码已失效！");
        }
        //3.如果不一致，直接返回错误信息
        if (!validateCode.equals(code)) {
            throw new CustomException("验证码错误！");
        }

        //4.判断当前登录的手机号是否存在数据库，如果不存在要去初始化该用户数据
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        User user = userService.getOne(wrapper);
        //如果是新用户，自动注册
        if (user == null) {
            user = new User();
            user.setName("user_"+phone);
            user.setPhone(phone);
            userService.save(user);
        }

        //5.返回登录成功，将userId缓存到session中（为了用户登录校验）
        session.setAttribute("userId", user.getId());
        return R.success("登录成功！");
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public R<String> loginOut(HttpSession session){
        session.removeAttribute("userId");
        return R.success("退出登录成功");
    }
}
